package com.tg.websocket;

import com.alibaba.fastjson.JSON;
import com.tg.pojo.Message;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@ServerEndpoint("/websocket/{username}")
@Component
public class WebSocket {
    static Logger logger = LoggerFactory.getLogger(WebSocket.class);
    private String username;

    //存储Session对象
    private static final ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<>();

    //存储暂存消息
    private static final ConcurrentHashMap<String, List<String>> messageMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws InterruptedException {
        this.username = username;
        if (map.containsKey(username)) {
            map.remove(username);
            map.put(username, session);
        } else {
            map.put(username, session);
        }
        logger.info("{}连接成功!", username);

        //判断当前用户是否有暂存消息
        if (messageMap.containsKey(username)){
            List<String> list = messageMap.get(username);
            if (list == null || list.isEmpty()){
                logger.warn("{}没有暂存消息!", username);
            } else {
                System.out.println(list);
                Thread.sleep(500);
                list.forEach(this::senMessage);
                logger.info("{}已成功收到暂存消息", username);
                list.clear();
            }
        }
    }

    @OnClose
    public void onClose() {
        if (map.containsKey(username)) {
            logger.warn("{}断开连接!", username);
        }
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(Session session, String messageJson) {
        senMessage(messageJson);
    }

    public void senMessage(String messageJson) {
        //用户在线
        Message message = JSON.parseObject(messageJson, Message.class);
        String toUsername = message.getToUsername();
        Session toSession = map.get(toUsername);
        if (!Objects.isNull(toSession)) {
            if (toSession.isOpen()) {
                toSession.getAsyncRemote().sendText(messageJson);
                logger.info("{}发送成功{}", message.getFromUsername(), message.getToUsername());
            } else {
                //用户离线，暂存消息
                List<String> list = messageMap.computeIfAbsent(toUsername, k -> new CopyOnWriteArrayList<>());
                list.add(messageJson);
                logger.info("{}暂存消息成功!", toUsername);
            }
        } else {
            logger.error("{}用户不存在!", toUsername);
        }
    }
}